<template>
    <div>

        <div @click="visible = true" class="select-btn">
            <span v-if="lng">{{ lng }} ; {{ lat }}</span>
        </div>
        <!-- <div>{{ points }}</div> -->
        <a-modal :open="visible" title="选择坐标点" :destroyOnClose="true" :width="1000" @ok="handleOk"
            @cancel="handleClose">

            <div v-if="lnglat" class="point-div">已选择坐标，
                经度：<span class="point-text">{{ lnglat.lng }}</span>；
                纬度：<span class="point-text">{{ lnglat.lat }}</span>；
            </div>

            <Amap ref="amap" @complete="complete" @click="handleClick" style="height: 500px;"></Amap>


            <div v-show="drawTip" id="drawTip" class="draw-tip">
                <div class="draw-tip-text"> 鼠标左键点击地图绘制区域，双击击鼠标左键结束绘制 </div>
            </div>

            <div class="oper">
                <!-- <div class="tip-text">人员进入围栏后，开启室内定位</div> -->
                 <a-space>
                    <a-button @click="drawPolygon" type="primary" class="btn">开始添加范围</a-button>

                    <a-button @click="deletePolygon" class="btn">重置</a-button>
                </a-space>
            </div>
        </a-modal>
    </div>
</template>
<script setup lang="ts">
import { ref, watch } from 'vue'
import Amap from '@/components/Amap/Amap.vue'
import location from '@/assets/map/location.png'
import { Form, message } from "ant-design-vue";

import { addBaseRange, addMarkerAndText } from '@/components/Amap/fenceUtils'
const formItemContext = Form.useInjectFormItemContext();
const lng = defineModel<number>('lng')
const lat = defineModel<number>('lat')
const points = defineModel<{ lng: number, lat: number }[]>('points')

const visible = ref(false)
const emit = defineEmits(['ok', 'close'])
const lnglat = ref<{ lng?: number, lat?: number }>({})
let map: AMap.Map
let drawTip = ref(false);
let mouseTool: AMap.MouseTool;
let overlays = []
let path: AMap.LngLat[] = []

const complete = (e: AMap.Map) => {
    map = e

    if (lng.value && lat.value) {
        handleClick({
            lnglat: {
                lng: lng.value,
                lat: lat.value
            }
        })
        map.setFitView()
    }

    mouseTool = new AMap.MouseTool(map);
    mouseTool.on('draw', (e) => {

        mouseTool.close(true);
        drawTip.value = false;
        path = [];
        for (var p of e.obj.getPath()) {
            path.push(p);
        }
        addPolygon(path)

    });

    if(points.value && points.value.length > 0){
        path = []
        for(let p of points.value){
            let lngLat= new AMap.LngLat(p.lng, p.lat)
            path.push(lngLat)
        }
        addPolygon(path)
        map.setFitView()
    }
}

const handleClick = (e: any) => {
    if (drawTip.value) {
        return
    }

    console.log(e)
    lnglat.value = e.lnglat
    let overlays = map.getAllOverlays()
    for (let item of overlays) {

        let extData = item.getExtData()
        if (extData.className == 'clickPoint') {
            map.remove(item);
        }
    }

    var icon = new AMap.Icon({
        size: new AMap.Size(23, 31), // 图标尺寸
        image: location, // Icon的图像
        imageSize: new AMap.Size(23, 31),
    });

    // 将 Icon 实例添加到 marker 上:
    var marker = new AMap.Marker({
        position: new AMap.LngLat(e.lnglat.lng, e.lnglat.lat),
        offset: new AMap.Pixel(0, 0), // 设置点标记偏移量
        anchor: 'bottom-center', // 设置锚点方位
        icon: icon, // 添加 Icon 实例
        extData: { className: 'clickPoint' }
    });

    map.add(marker);
}

const handleOk = () => {
    emit('ok', lnglat.value)
    lng.value = lnglat.value.lng
    lat.value = lnglat.value.lat
    points.value = path.map(item => {
        return {
            lng: item.lng,
            lat: item.lat
        }
    })
    formItemContext.onFieldChange()
    handleClose()

}
const handleClose = () => {
    lnglat.value = {}
    visible.value = false
}


const drawPolygon = () => {

    mouseTool.polygon({
        fillColor: '#d6333f',
        strokeColor: '#d6333f',
        //同Polygon的Option设置
    });
    drawTip.value = true;
};

const deletePolygon = () => {
    mouseTool.close(true);
    drawTip.value = false;

    message.success('已重置');

    map.clearMap();
    overlays = []
    path = []

    drawPolygon()
};


const addPolygon = (path: AMap.LngLat[], id?: number) => {
    let poly = new AMap.Polygon();
    poly.setOptions({

        path: path, //设置多边形边界路径
        strokeColor: '#EB5B5B', //线颜色
        strokeOpacity: 0.9, //线透明度
        strokeWeight: 1, //线宽
        fillColor: '#FA5151', //填充色
        fillOpacity: 0.5, //填充透明度

        extData: { id: id }
    })

    poly.on('click', (e) => {
        handleClick(e)
    })

    map.add(poly)

    overlays.push(poly);

    
}


</script>
<style scoped>
.point-div {

    height: 50px;
    line-height: 50px;
}

.point-text {
    color: #1677ff;
}

.select-btn {
    position: relative;
    border: 1px solid #d9d9d9;
    border-radius: 2px;
    box-sizing: border-box;
    margin: 0;
    padding: 3px 11px;
    color: rgba(0, 0, 0, 0.88);
    font-size: 16px;
    height: 32px;
    cursor: pointer;
}


@keyframes beat {
    0% {
        transform: scale(1, 1);
    }

    50% {
        transform: scale(1.1, 1.1);
    }

    100% {
        transform: scale(1, 1);
    }
}

@-moz-keyframes beat

/* Firefox */
    {
    0% {
        transform: scale(1, 1);
    }

    50% {
        transform: scale(1.1, 1.1);
    }

    100% {
        transform: scale(1, 1);
    }
}

@-webkit-keyframes beat

/* Safari 和 Chrome */
    {
    0% {
        transform: scale(1, 1);
    }

    50% {
        transform: scale(1.1, 1.1);
    }

    100% {
        transform: scale(1, 1);
    }
}

@-o-keyframes beat

/* Opera */
    {
    0% {
        transform: scale(1, 1);
    }

    50% {
        transform: scale(1.1, 1.1);
    }

    100% {
        transform: scale(1, 1);
    }
}

.draw-tip {
    position: absolute;
    right: 20px;
    bottom: 100px;
    padding: 10px 20px;
    z-index: 10;
    background: #fff;
    box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.5);
}

.draw-tip-text {
    color: #e73d4a;
    animation: beat 1s infinite;
    -moz-animation: beat 1s infinite;
    /* Firefox */
    -webkit-animation: beat 1s infinite;
    /* Safari 和 Chrome */
    -o-animation: beat 1s infinite;
}

.tip-text {
    display: inline-block;
    padding: 0 40px 0 0;
}
.oper {
    padding: 20px 0; text-align: right;
  }
</style>